//
//  ChangeInfoViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 3/8/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ChangeInfoViewController.h"
#import "WDUsers.h"
#import "ZHWebService.h"
#import "ZHDataService.h"
#import "TextFieldViewController.h"
#import "ActivityViewManager.h"
#import "NSString+Utilities.h"
#import "AddressViewController.h"
#import "JSON.h"
#import "LoginViewController.h"
#import "RootViewController.h"
#import "PersonalViewController.h"


@interface ChangeInfoViewController()

@property (nonatomic, retain) NSDictionary *addressDict;
@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *city;

- (void)getLoginUser;
- (void)getNewUser;
- (NSString *)checkFieldContent;
- (void)changeUserInfoForPurpose:(ViewType)type;

@end

@implementation ChangeInfoViewController

@synthesize addressDict;
@synthesize province,city;
@synthesize changeUser;
@synthesize changedPwd;
@synthesize viewType;
@synthesize repeatPassword,password;
@synthesize addrView,picker;

#pragma mark - my methods
- (void)getLoginUser
{
    WDUsers *user = [[WDUsers alloc] init];
    self.changeUser = user;
    [user release];
    self.changeUser.userName = [[ZHDataService sharedService] loginUser].userName;
    self.changeUser.userEmail = [[ZHDataService sharedService] loginUser].userEmail;
    self.changeUser.userProvince = [[ZHDataService sharedService] loginUser].userProvince;
    self.changeUser.userCity = [[ZHDataService sharedService] loginUser].userCity;
    self.changeUser.userPwd = [[ZHDataService sharedService] loginUser].userPwd;
    
    
    UITextField* textField = (UITextField*)[self.view viewWithTag:kUsername];
    if ([self.changeUser.userName length]>0) {
        textField.text = self.changeUser.userName;
    }
    
    textField = (UITextField*)[self.view viewWithTag:kMail];
    if ([self.changeUser.userEmail length]>0) {
        textField.text = self.changeUser.userEmail;
    }
    
    textField = (UITextField*)[self.view viewWithTag:kAddr];
    if ([self.changeUser.userProvince length]>0&&[self.changeUser.userCity length]>0) {
        textField.text = [NSString stringWithFormat:@"%@ %@",self.changeUser.userProvince,self.changeUser.userCity];
    }
    
    
    
}

- (void)getNewUser
{
    WDUsers *user = [[WDUsers alloc] init];
    user.userName = @"";
    user.userEmail = @"";
    user.userProvince = @"";
    user.userCity = @"";
    user.userPwd = @"";
    self.changeUser = user;
    [user release];
}

- (NSString *)checkFieldContent
{
    if(self.changeUser.userName == nil || [self.changeUser.userName isEqualToString:@""])
        return @"用户名不能为空！";
    if(self.viewType == kViewEdit)
    {
        if(self.changeUser.userPwd == nil || [self.changeUser.userPwd isEqualToString:@""])
            return @"原密码字段不能为空！";
    }
    else
    {
        if(self.changeUser.userPwd == nil || [self.changeUser.userPwd isEqualToString:@""])
            return @"原密码字段不能为空！";
        if(![self.changeUser.userPwd isEqualToString:self.changedPwd])
            return @"两次输入的密码不一致！";
    }
    
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    if(![self.changeUser.userEmail checkWithRegex:regex])
        return @"邮箱格式不正确！";
    if(self.changeUser.userProvince == nil || [self.changeUser.userProvince isEqualToString:@""])
        return @"地址不能为空！";
    return nil;
}

- (void)changeUserInfoForPurpose:(ViewType)type
{
    CompletionBlock completion = ^(NSData *data){
        NSString *result = [ZHDataService changeUserInfoWithData:data];
        
        NSRange range = [result rangeOfString:@"注册成功"];
        
        if(range.length != 0)
        {
            UIAlertView *alertView  = [[UIAlertView alloc] initWithTitle:@"注册成功" message:@"现在帮您跳转到" delegate:self cancelButtonTitle:@"个人中心" otherButtonTitles:@"论坛", nil];
            [alertView show];
            [alertView release];
            return;
        }
        else
            [ActivityViewManager showErrorViewWithMessage:result];
    };
    ErrorBlock error = ^(NSString *error){
        
        NSLog(@"error = %@",error);
    
    };
    
    if(type == kViewEdit)
    {
        if(self.changedPwd == nil)
            self.changedPwd = @"";
        
        [[ZHWebService sharedService] changeUserInfoWithName:self.changeUser.userName 
                                                      oldPwd:self.changeUser.userPwd 
                                                    province:self.changeUser.userProvince 
                                                       email:self.changeUser.userEmail 
                                                      newPwd:self.changedPwd 
                                                        city:self.changeUser.userCity 
                                                onCompletion:completion 
                                                     onError:error];
    }
    else
    {
        [[ZHWebService sharedService] registerUserWithName:self.changeUser.userName 
                                                  password:self.changeUser.userPwd 
                                                     email:self.changeUser.userEmail 
                                                  province:self.changeUser.userProvince 
                                                      city:self.changeUser.userCity 
                                              onCompletion:completion 
                                                   onError:error];
    }
}

#pragma mark - UIAlertViewDelegate methods
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginController = (LoginViewController *)[self.navigationController presentingViewController];
    RootViewController *rootController = (RootViewController *)[loginController presentingViewController];
    PersonalViewController *personController = (PersonalViewController *)[(UINavigationController *)[rootController selectedViewController] topViewController];
    personController.username = self.changeUser.userName;
    personController.password = self.changeUser.userPwd;
    personController.currentTab = kPersonalComprehensiveTab;
    [ZHDataService sharedService].loginUser.userId = @"registered";
    if (buttonIndex==0) {
    }
    else {
        rootController.selectedIndex = 2;
    }
    [rootController dismissModalViewControllerAnimated:YES];
}

#pragma mark - AbstractTabViewController methods
- (void)leftItemClicked
{
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (void)rightItemClicked
{
    UITextField* textField = nil;
    
    for (NSInteger i = kUsername; i <= kAddr; i++) {
        textField = (UITextField*)[self.view viewWithTag:i];
        if ([textField isFirstResponder]) {
            [textField resignFirstResponder];
            break;
        }
    }
    
    self.addrView.frame = CGRectMake(0, 416, 320, 216);
    
    textField = (UITextField*)[self.view viewWithTag:kUsername];
    self.changeUser.userName = textField.text;
    
    textField = (UITextField*)[self.view viewWithTag:kPassword];
    self.changeUser.userPwd = textField.text;
    
    textField = (UITextField*)[self.view viewWithTag:kRepeatPassword];
    self.changedPwd = textField.text;

    textField = (UITextField*)[self.view viewWithTag:kMail];
    self.changeUser.userEmail = textField.text;
    
    textField = (UITextField*)[self.view viewWithTag:kAddr];
    self.changeUser.userProvince = textField.text;


    NSString *result = [self checkFieldContent];
    if(nil != result)
        [ActivityViewManager showErrorViewWithMessage:result];
    //requst to change info
    else
    {
        [self changeUserInfoForPurpose:self.viewType];
    }
}

#pragma mark - View lifecycle
- (void)dealloc
{
    
    
    [picker release];
    [addrView release];
    [password release];
    [repeatPassword release];
    [changedPwd release];
    [changeUser release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSInteger rowForOne = [[self.addressDict allKeys] indexOfObject:self.province];
    NSInteger rowForTwo = [[self.addressDict objectForKey:self.province] indexOfObject:self.city];
    
    [self.picker selectRow:rowForOne inComponent:0 animated:YES];
    [self.picker reloadComponent:1];
    [self.picker selectRow:rowForTwo inComponent:1 animated:YES];

    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(self.viewType == kViewEdit)
    {
        self.title = @"修改信息";
        [self setBackgroundImageViewForTabView];
        self.password.text = @"原密码";
        self.repeatPassword.text = @"新密码";
        [self getLoginUser];
    }
    else
    {
        self.title = @"注册新用户";
        [self setBackgroundImageViewForRegisterView];
        [self addNaviBarLeftItemWithTitle:@"取消"];
        self.password.text = @"密码";
        self.repeatPassword.text = @"重复密码";
        
        [self getNewUser];
    }
    [self addNaviBarRightItemWithTitle:@"提交"];
    
    UITextField* username = (UITextField*)[self.view viewWithTag:kUsername];
    if (username!=nil&&![username isFirstResponder]) {
        [username becomeFirstResponder];
    }
    
    

    if(self.viewType == kViewEdit)
        [self setBackgroundImageViewForTabView];
    else
    {
        [self setBackgroundImageViewForRegisterView];
        //set approprite frame for subviews
//        CGRect rect = self.myTableView.frame;
//        rect.origin.y += 20.f;
//        self.myTableView.frame = rect;
//        rect = self.picker.frame;
//        rect.origin.y += 49.f;
//        self.picker.frame = rect;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Provinces_Cities" ofType:@"txt"];
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    self.addressDict = [str JSONValue];
    [str release];
    self.province = self.changeUser.userProvince;
    self.city = self.changeUser.userCity;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.changeUser = nil;
    self.repeatPassword = nil;
    self.password = nil;
    self.addrView = nil;
    self.picker = nil;
    
}

#pragma mark - UIPickViewDatasource methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == 0)
        return [[self.addressDict allKeys] count];
    NSInteger row = [pickerView selectedRowInComponent:0];
    NSString *key = [[self.addressDict allKeys] objectAtIndex:row];
    NSArray *values = [self.addressDict objectForKey:key];
    return [values count];
}
#pragma mark - UIPickViewDelegate methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0)
    {
        NSArray *keys = [self.addressDict allKeys];
        return [keys objectAtIndex:row];
    }
    NSInteger selectedRow = [pickerView selectedRowInComponent:0];
    NSString *key = [[self.addressDict allKeys] objectAtIndex:selectedRow];
    NSArray *values = [self.addressDict objectForKey:key];
    return [values objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component == 0)
    {
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
        [self pickerView:pickerView didSelectRow:0 inComponent:1];
    }
    else
    {
        NSInteger rowForOne = [pickerView selectedRowInComponent:0];
        NSString *key = [[self.addressDict allKeys] objectAtIndex:rowForOne];
        NSString *value = [[self.addressDict objectForKey:key] objectAtIndex:row];
        self.province = key;
        self.city = value;
        
        UITextField* addr = (UITextField*)[self.view viewWithTag:kAddr];
        addr.text = [NSString stringWithFormat:@"%@ %@",self.province,self.city];

    }
}

- (IBAction)addrClick:(id)sender
{
    for (NSInteger i = kUsername; i <= kAddr; i++) {
        UITextField* textField = (UITextField*)[self.view viewWithTag:i];
        if ([textField isFirstResponder]) {
            [textField resignFirstResponder];
            break;
        }
    }
    
    UITextField* textField = (UITextField*)[self.view viewWithTag:kAddr];
    if ([textField.text length]==0) {
        NSString *key = [[self.addressDict allKeys] objectAtIndex:0];
        NSString *value = [[self.addressDict objectForKey:key] objectAtIndex:0];
        self.province = key;
        self.city = value;
        
        textField.text = [NSString stringWithFormat:@"%@ %@",self.province,self.city];
    }
    
    if (self.addrView.frame.origin.y == 416) {
        
        [UIView beginAnimations:@"" context:nil];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.1];
        
        self.addrView.frame = CGRectMake(0, 200, 320, 216);
        
        [UIView commitAnimations];
        
        
        
    }
    
    
}

#pragma mark - UITableViewDataSource methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    
    CGRect frame = self.addrView.frame;
    
    if (textField.tag == kAddr) {
        frame.origin.y = 200;
        [UIView beginAnimations:@"" context:nil];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.2];
        self.addrView.frame = frame;
        [UIView commitAnimations];
        return NO;
    }
    
    
    if (frame.origin.y == 200) {
        [UIView beginAnimations:@"" context:nil];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.2];
        
        frame.origin.y += 216;
        self.addrView.frame = frame;
        
        [UIView commitAnimations];
    }
    
    
    
    
    return YES;
}




@end
